package com.apobates.jforum.grief.schema2doc.reactive.schema;

import com.apobates.jforum.grief.schema2doc.core.SchemaTableStrategy;
import com.apobates.jforum.grief.schema2doc.core.entity.Column;
import com.apobates.jforum.grief.schema2doc.core.entity.Table;
import com.apobates.jforum.grief.schema2doc.core.schema.SchemaDialect;
import com.apobates.jforum.grief.schema2doc.reactive.SchemaQueryFlowableResult;
import io.reactivex.Flowable;
import io.reactivex.Single;
import org.davidmoten.rx.jdbc.Database;
import java.util.List;
import java.util.Optional;

public abstract class AbstractRxJavaQueryExecutor implements SchemaQueryFlowableResult {
    private final Database db;
    private final SchemaDialect dialect;

    protected AbstractRxJavaQueryExecutor(Database db, SchemaDialect dialect) {
        this.db = db;
        this.dialect = dialect;
    }

    @Override
    public Flowable<Table> getAll(Optional<String> dbName, Optional<String> schema, SchemaTableStrategy tableStrategy) {
        try {
            dialect.validate(dbName, schema);
        }catch (IllegalArgumentException e) {
            return Flowable.error(e);
        }
        return getTables(db, dbName, schema, tableStrategy);
    }

    @Override
    public Single<List<Column>> getTableColumn(Table table) {
        return getColumns(db, table);
    }

    /**
     * 返回所有导出的表信息
     * @param db RxJdbc.Database 实例
     * @param dbName 数据名称
     * @param schema 模式名称
     * @param tableStrategy
     * @return
     * @throws IllegalArgumentException 若数据库名称或模式名称是必须的但不用名抛出
     */
    protected abstract Flowable<Table> getTables(Database db, Optional<String> dbName, Optional<String> schema, SchemaTableStrategy tableStrategy) throws IllegalArgumentException;

    /**
     * 返回指定表的所有导出列信息
     * @param db RxJdbc.Database 实例
     * @param table 表 实例
     * @return
     */
    protected abstract Single<List<Column>> getColumns(Database db, Table table);
}
